using System;
using AleaClasses;
using System.Collections;

namespace AleaPlayer
{
	public delegate void TAleaPlayerMessageDelegate(string aMessage);

	public class TAleaPlayer
	{
		public TAleaPlayer(TAleaGraph aAleaGraph)
		{
			fAleaGraph = aAleaGraph;
		}

		private TAleaGraph fAleaGraph;
		private TAleaPlayerMessageDelegate fAleaPlayerMessageDelegate = null;
		private bool fStop = false;
		private ArrayList fDriveLabels = new ArrayList();

		public TAleaGraph AleaGraph
		{
			get
			{
				return fAleaGraph;
			}
		}

		public TAleaPlayerMessageDelegate AleaPlayerMessageDelegate
		{
			get
			{
				return fAleaPlayerMessageDelegate;
			}
			set
			{
				fAleaPlayerMessageDelegate = value;
			}
		}

		public void Stop()
		{
			fStop = true;
		}

		public void AddDriveLabel(string aDriveLabel)
		{
			fDriveLabels.Add(aDriveLabel);
		}

		public void ClearDriveLabels()
		{
			fDriveLabels.Clear();
		}

		public void DeleteDriveLabel(string aDriveLabel)
		{
			fDriveLabels.Remove(aDriveLabel);
		}

		public ArrayList DriveLabels
		{
			get
			{
				return fDriveLabels;
			}
			set
			{
				fDriveLabels = value;
			}
		}

		public TNode Play(TNode aNode)
		{
			TNode retval = null;

			if (aNode == null)
			{
				aNode = AleaGraph.StartNode;
				if ((aNode == null) && (AleaGraph.Nodes.Count > 0))
					aNode = AleaGraph.Nodes[0];
			}

			if (aNode != null)
			{
				// Load File
				SendMessage("Node: " + aNode.DisplayName);
				SendMessage("Load and play the file " + aNode.FileName);
				//System.Threading.Thread.Sleep(1000);
				TAleaWavPlayer WavPlayer = new TAleaWavPlayer();
				WavPlayer.Play(aNode.FileName, 0);

				// Clearing Drive Labels
				if (aNode.ArrivalLabels != null)
				{
					foreach(TLabel lArrivalLabel in aNode.ArrivalLabels)
					{
						if (fDriveLabels.Contains(lArrivalLabel.LabelCode))
						{
							SendMessage("Reached Label " + lArrivalLabel.DisplayName);
							fDriveLabels.Remove(lArrivalLabel.LabelCode);
						}
					}
				};

				// Get next node
				retval = aNode.GetNextNode(fDriveLabels);
			}

			if (retval == null)
				SendMessage("Done");
			else
				SendMessage("Next Node is " + retval.DisplayName);

			return retval;
		}

		private void SendMessage(string aMessage)
		{
			if (AleaPlayerMessageDelegate != null)
			{
				AleaPlayerMessageDelegate(DateTime.Now.ToString() + ": " + aMessage);
			}
		}
	}
}
